package com.jackson.engineeringtechnologyguide.Transcation.service;

/*
 * Author: JacksonCoder
 * FileName: BankService
 * Version: 1.0.0
 * Date: 2025/1/11
 */

import com.jackson.engineeringtechnologyguide.Transcation.model.Account;
import com.jackson.engineeringtechnologyguide.Transcation.repository.AccountRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;

@Service
public class BankService {
    @Autowired
    private AccountRepository accountRepository;

    @Autowired
    private PlatformTransactionManager transactionManager;

    public void transferMoney(String fromAccountName, String toAccountName, double amount) {
        // 定义事务属性
        TransactionDefinition definition = new DefaultTransactionDefinition();
        TransactionStatus status = transactionManager.getTransaction(definition);

        try {
            // 查找转出账户
            Account fromAccount = accountRepository.findByName(fromAccountName);
            if (fromAccount == null) {
                throw new RuntimeException("转出账户不存在");
            }

            // 查找转入账户
            Account toAccount = accountRepository.findByName(toAccountName);
            if (toAccount == null) {
                throw new RuntimeException("转入账户不存在");
            }

            // 检查转出账户余额是否充足
            if (fromAccount.getBalance() < amount) {
                throw new RuntimeException("余额不足");
            }

            // 扣款
            fromAccount.setBalance(fromAccount.getBalance() - amount);
            accountRepository.save(fromAccount);

            // 模拟异常，测试事务回滚
            if (amount > 1000) {
                throw new RuntimeException("转账金额过大，操作取消");
            }

            // 加款
            toAccount.setBalance(toAccount.getBalance() + amount);
            accountRepository.save(toAccount);

            // 提交事务
            transactionManager.commit(status);
        } catch (Exception e) {
            // 回滚事务
            transactionManager.rollback(status);
            throw e;
        }
    }
}
